package com.zt.controller.servlet;

import com.zt.business.service.UserService;
import com.zt.business.vo.ResponseData;
import com.zt.controller.annotation.MethodType;
import com.zt.controller.annotation.RequestMethod;
import com.zt.model.util.ConstUtil;
import com.zt.model.util.MD5Util;
import com.zt.model.util.VerifyCodeUtil;
import lombok.extern.log4j.Log4j2;

import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import java.awt.image.BufferedImage;

@Log4j2
@WebServlet(name = "loginServlet",urlPatterns = "/sys/login/*")
public class LoginServlet extends BaseServlet {

    private UserService userService = new UserService();

    @RequestMethod(value = "/sys/login/login",method = MethodType.POST)
    public void login() throws Exception{
        //请求参数
        String logName = request.getParameter("logName");
        String logPwd = request.getParameter("logPwd");
        String code = request.getParameter("code");

        //获取Session中的验证码
        Object sessionCode = session.getAttribute(ConstUtil.VERIFY_CODE);
        ResponseData data = userService.login(logName,MD5Util.getStringMD5(logPwd),code,sessionCode);
        //登录成功
        if(data.getCode() == 0){
            session.setAttribute(ConstUtil.CURRENT_USER,data.getData());
        }
        //响应Ajax信息
        responseAjax(data);
    }

    @RequestMethod("/sys/login/loginOut")
    public void loginOut() throws Exception{
        session.invalidate();
        response.sendRedirect("/login.jsp");
    }

    @RequestMethod("/sys/login/verifyCode")
    public void verifyCode() throws Exception{
        //1.生成验证码图片
        BufferedImage img = VerifyCodeUtil.drawImg();
        //2.获取验证码字符串，并将随机数存在session中
        session.setAttribute(ConstUtil.VERIFY_CODE,VerifyCodeUtil.getVerifyCode());
        //3.设置响应头通知浏览器以图片的形式打开
        response.setContentType("image/jpeg");//等同于response.setHeader("Content-Type", "image/jpeg");
        //4.设置响应头控制浏览器不要缓存
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        //5.将图片写给浏览器
        ImageIO.write(img, "jpg", response.getOutputStream());
    }

}
